package com.socialsoftware.ui.Contact;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.snackbar.Snackbar;
import com.socialsoftware.Page.AddFriendActivity;
import com.socialsoftware.Page.FriendProfileActivity;
import com.socialsoftware.R;
import com.socialsoftware.Page.SocialSoftwareApplication;
import com.socialsoftware.adapter.ContactAdapter;
import com.socialsoftware.databinding.FragmentContactsBinding;
import com.socialsoftware.model.Contact;
import com.socialsoftware.repository.ContactRepository;
import com.socialsoftware.util.ContactSyncManager;
import com.socialsoftware.util.SessionManager;

import java.util.ArrayList;
import java.util.List;

public class ContactsFragment extends Fragment implements ContactAdapter.OnContactClickListener {

    private static final String TAG = "ContactsFragment";
    private FragmentContactsBinding binding;
    private ContactsViewModel contactsViewModel;
    private ContactAdapter contactAdapter;
    private List<Contact> contacts = new ArrayList<>();
    private ContactSyncManager syncManager;
    private SessionManager sessionManager;
    private ContactRepository contactRepository;

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        // Initialize SessionManager
        sessionManager = SessionManager.getInstance(requireContext());
        
        // Get application and initialize repositories
        Application application = requireActivity().getApplication();
        
        // Initialize ContactRepository and SyncManager
        if (application instanceof SocialSoftwareApplication) {
            // Use the custom application if available
            SocialSoftwareApplication socialSoftwareApp = (SocialSoftwareApplication) application;
            contactRepository = socialSoftwareApp.getContactRepository();
        } else {
            // Fallback: create a new repository directly
            Log.w(TAG, "SocialSoftwareApplication not found, creating repository directly");
            contactRepository = new ContactRepository(application);
        }
        
        syncManager = new ContactSyncManager(requireContext(), contactRepository);
        
        // Create the ViewModel using a factory
        ContactsViewModelFactory factory = new ContactsViewModelFactory(application);
        contactsViewModel = new ViewModelProvider(this, factory).get(ContactsViewModel.class);

        binding = FragmentContactsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 不启用选项菜单（移除三点菜单）
        setHasOptionsMenu(false);

        initViews();
        setupRecyclerView();
        setupSidebarIndex();
        setupSwipeRefresh();
        observeViewModel();

        return root;
    }

    private void initViews() {
        binding.progressBar.setVisibility(View.VISIBLE);
    }

    private void setupRecyclerView() {
        contactAdapter = new ContactAdapter(requireContext(), contacts);
        contactAdapter.setOnContactClickListener(this);

        binding.recyclerViewContacts.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.recyclerViewContacts.setAdapter(contactAdapter);
    }
    
    private void setupSidebarIndex() {
        SidebarIndexView sidebarIndexView = binding.sidebarIndex;
        sidebarIndexView.setOnLetterSelectedListener(contactAdapter);
        sidebarIndexView.setRecyclerView(binding.recyclerViewContacts);
        sidebarIndexView.setIndicatorTextView(binding.tvLetterIndicator);
    }
    
    private void setupSwipeRefresh() {
        binding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 从服务器刷新联系人数据
                Log.d(TAG, "用户下拉刷新，从服务器获取好友数据");
                contactRepository.fetchFriendsFromServer();
            }
        });
    }
    
    private void observeViewModel() {
        // 观察联系人数据变化
        contactsViewModel.getContacts().observe(getViewLifecycleOwner(), new Observer<List<Contact>>() {
            @Override
            public void onChanged(List<Contact> contactList) {
                contacts.clear();
                if (contactList != null) {
                    contacts.addAll(contactList);
                    Log.d(TAG, "联系人数据已更新，数量: " + contactList.size());
                }
                contactAdapter.notifyDataSetChanged();
            }
        });

        // 观察加载状态
        contactsViewModel.getIsLoading().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean isLoading) {
                binding.progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
                binding.swipeRefreshLayout.setRefreshing(isLoading);
                
                if (isLoading) {
                    Log.d(TAG, "正在加载联系人数据...");
                } else {
                    Log.d(TAG, "联系人数据加载完成");
                }
            }
        });
        
        // 同时观察仓库的加载状态
        contactRepository.getIsLoading().observe(getViewLifecycleOwner(), isLoading -> {
            if (isLoading) {
                binding.swipeRefreshLayout.setRefreshing(true);
            } else {
                binding.swipeRefreshLayout.setRefreshing(false);
            }
        });
        
        // 观察错误消息
        contactsViewModel.getErrorMessage().observe(getViewLifecycleOwner(), errorMessage -> {
            if (!TextUtils.isEmpty(errorMessage)) {
                Log.e(TAG, "获取联系人数据出错: " + errorMessage);
                
                // 显示错误提示
                Snackbar.make(binding.getRoot(), errorMessage, Snackbar.LENGTH_LONG)
                        .setAction("重试", v -> contactsViewModel.loadContacts())
                        .show();
            }
        });
        
        // 同时观察仓库的错误消息
        contactRepository.getErrorMessage().observe(getViewLifecycleOwner(), errorMessage -> {
            if (!TextUtils.isEmpty(errorMessage)) {
                Log.e(TAG, "仓库获取联系人数据出错: " + errorMessage);
                
                // 显示用户友好的错误提示
                String userFriendlyMessage = getUserFriendlyErrorMessage(errorMessage);
                
                Snackbar.make(binding.getRoot(), userFriendlyMessage, Snackbar.LENGTH_LONG)
                        .setAction("重试", v -> contactRepository.fetchFriendsFromServer())
                        .show();
            }
        });
    }
    
    private static final int REQUEST_FRIEND_PROFILE = 1001;
    
    @Override
    public void onContactClick(Contact contact) {
        // 处理联系人点击事件
        if (contact.getType() == Contact.TYPE_SPECIAL) {
            // 处理特殊联系人点击（新的朋友、群聊等）
            handleSpecialContactClick(contact);
        } else if (contact.getType() == Contact.TYPE_HEADER) {
            // 不处理头部项目的点击
            return;
        } else {
            // 处理普通联系人点击 - 打开联系人详情
            Intent intent = new Intent(requireContext(), FriendProfileActivity.class);
            
            // 规范化联系人ID - 如果包含小数点，则转换为整数
            String contactId = contact.getId();
            String contactname=contact.getName();
            if (contactId != null && contactId.contains(".")) {
                try {
                    // 尝试将浮点数转换为整数（去除小数部分）
                    contactId = String.valueOf((int)Double.parseDouble(contactId));
                    Log.d(TAG, "规范化联系人ID: " + contact.getId() + " -> " + contactId);
                } catch (NumberFormatException e) {
                    // 如果转换失败，保留原始ID
                    Log.w(TAG, "无法规范化联系人ID: " + contact.getId()+"用户名："+contact.getName(),e);
                }
            }
            
            // 传递联系人ID和用户名
            intent.putExtra("contact_id", contactId);
            intent.putExtra("contact_username", contact.getName());
            
            // 优先使用备注名(remark)，如果备注名为空则使用名称(name)
            String displayName = contact.getRemark();
            if (displayName == null || displayName.isEmpty()) {
                displayName = contact.getName();
            }
            intent.putExtra("contact_name", displayName);
            
            Log.d(TAG, "打开联系人详情，ID: " + contactId + ", 昵称: " + displayName+"用户名："+contactname);
            startActivity(intent);
            requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        // 刷新联系人列表，以确保显示最新的数据
        if (contactsViewModel != null) {
            Log.d(TAG, "Fragment恢复，加载联系人数据");
            contactsViewModel.loadContacts();
        }
    }
    
    /**
     * 处理特殊联系人项目的点击
     * @param contact 特殊联系人
     */
    private void handleSpecialContactClick(Contact contact) {
        String name = contact.getName();
        String message = "";
        
        switch (name) {
            case "新的朋友":
                message = "打开新的朋友页面";
                // 打开添加好友页面
                Intent intent = new Intent(requireContext(), AddFriendActivity.class);
                startActivity(intent);
                return;
            case "群聊":
                message = "打开群聊列表";
                break;
            case "标签":
                message = "打开标签页面";
                break;
            case "公众号":
                message = "打开公众号列表";
                break;
            default:
                message = "点击了: " + name;
                break;
        }
        
        Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLetterSelected(String letter, int position) {
        // Scroll to the position of the selected letter
        binding.recyclerViewContacts.scrollToPosition(position);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    /**
     * 将技术错误消息转换为用户友好的错误消息
     * @param errorMessage 原始错误消息
     * @return 用户友好的错误消息
     */
    private String getUserFriendlyErrorMessage(String errorMessage) {
        if (errorMessage == null) {
            return "未知错误，请稍后重试";
        }
        
        // 处理常见错误类型
        if (errorMessage.contains("404") || errorMessage.contains("找不到")) {
            return "服务器暂时无法提供好友列表，请稍后重试";
        } else if (errorMessage.contains("网络") || errorMessage.contains("连接")) {
            return "网络连接问题，请检查您的网络设置";
        } else if (errorMessage.contains("超时")) {
            return "请求超时，请稍后重试";
        } else if (errorMessage.contains("认证") || errorMessage.contains("登录") || errorMessage.contains("令牌")) {
            return "登录信息已过期，请重新登录";
        } else if (errorMessage.contains("解析") || errorMessage.contains("数据")) {
            return "数据处理错误，请稍后重试";
        }
        
        // 默认错误消息
        return "获取联系人列表失败，请稍后重试";
    }
}